package com.movitech.mobile.ddzy.modules.bpm.bizservice.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.entity.WStrategicProtocol;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWStrategicProtocol;
import com.movitech.mobile.cz.base.purchase.service.WStrategicProtocolService;
import com.movitech.mobile.cz.base.supplier.entity.SSuppliersLastThreeAchieve;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSSuppliers;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersLastThreeAchieveService;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.cz.base.sys.entity.SCompany;
import com.movitech.mobile.cz.base.sys.entity.SProject;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.entity.SysDict;
import com.movitech.mobile.cz.base.sys.service.SCompanyService;
import com.movitech.mobile.cz.base.sys.service.SProjectService;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.sys.service.SysDictService;
import com.movitech.mobile.cz.base.util.UserUtils;
import com.movitech.mobile.ddzy.bpm.feignclient.MbsDataAuthClient;
import com.movitech.mobile.ddzy.bpm.vo.MbsStrategicProtocols;
import com.movitech.mobile.ddzy.bpm.vo.MbsSupplierInternalPerformance;
import com.movitech.mobile.ddzy.modules.bpm.bizservice.BaseDataSynService;
import com.movitech.mobile.ddzy.modules.bpm.bizvo.MbsPcDataVo;
import com.movitech.mobile.ddzy.modules.bpm.bizvo.MbsPcTagDataVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("baseDataSynService")
public class BaseDataSynServiceImpl implements BaseDataSynService {

    @Value("${mbs.syn.data.url}")
    private String mbsSynDataUrl;

    @Autowired
    @Qualifier("sRegionalCompanyService")
    private SRegionalCompanyService sRegionalCompanyService;

    @Autowired
    @Qualifier("sProjectService")
    private SProjectService sProjectService;

    @Autowired
    @Qualifier("sCompanyService")
    private SCompanyService sCompanyService;

    @Autowired
    MbsDataAuthClient mbsDataAuthClient;

    @Autowired
    @Qualifier("sysDictService")
    private SysDictService sysDictService;

    @Autowired
    @Qualifier("sSuppliersLastThreeAchieveService")
    private SSuppliersLastThreeAchieveService sSuppliersLastThreeAchieveService;

    @Autowired
    @Qualifier("wStrategicProtocolService")
    private WStrategicProtocolService wStrategicProtocolService;

    @Autowired
    @Qualifier("sSuppliersService")
    private SSuppliersService sSuppliersService;

    /***
     * 从mbs同步地区公司和项目数据
     */
    @Override
    public void synRegionalCompanyAndProjectFromMBS() {
        try {
            String returnJson = HttpUtil.sendGet(mbsSynDataUrl);
            LicenseUtil.INSTANCE.validate();
            if (StringUtils.isNotEmpty(returnJson)) {
                Gson gson = new Gson();
                RestReturnResult<List<MbsPcTagDataVo>> result = gson.fromJson(returnJson, new TypeToken<RestReturnResult<List<MbsPcTagDataVo>>>() {
                }.getType());
                if (result != null) {
                    List<MbsPcTagDataVo> lstMbsPcTagDataVo = result.getData();
                    if (CollectionUtils.isNotEmpty(lstMbsPcTagDataVo)) {
                        Map<String, String> mapReginalCompany = Maps.newHashMap();
                        Map<String, SCompany> mapCompany = Maps.newHashMap();
                        for (MbsPcTagDataVo mbsPcTagDataVo : lstMbsPcTagDataVo) {

                            //保存地区公司
                            boolean isNew = true;
                            SRegionalCompany sRegionalCompany = null;

                            ///
                            List<SRegionalCompany> lstSRegionalCompany = sRegionalCompanyService.getRegionalCompanyByCode(mbsPcTagDataVo.getTagcode());
                            if (CollectionUtils.isNotEmpty(lstSRegionalCompany)) {
                                sRegionalCompany = lstSRegionalCompany.get(0);
                                isNew = false;
                            } else {
                                sRegionalCompany = new SRegionalCompany();
                            }
                            sRegionalCompany.setRegionalCompanyName(mbsPcTagDataVo.getTagname());
                            sRegionalCompany.setRegionalCompanyCode(mbsPcTagDataVo.getTagcode());
                            if (StringUtils.equalsIgnoreCase(mbsPcTagDataVo.getTagcode(), "ddzy")) {
                                sRegionalCompany.setRcType(1);//类型（1：集团，2：地区公司）
                            } else {
                                sRegionalCompany.setRcType(2);//
                            }
                            if (isNew) {
                                sRegionalCompany.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
                                sRegionalCompany.setId(IdGenUtils.uuid());
                                sRegionalCompanyService.insert(sRegionalCompany);
                            } else {
                                sRegionalCompany.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, false);
                                sRegionalCompanyService.updateById(sRegionalCompany);
                            }
                            mapReginalCompany.put(mbsPcTagDataVo.getTagcode(), sRegionalCompany.getId());

                            ///保存公司
                            if (CollectionUtils.isNotEmpty(mbsPcTagDataVo.getChildList())) {
                                for (MbsPcDataVo mbsPcDataVo : mbsPcTagDataVo.getChildList()) {
                                    if (StringUtils.equalsIgnoreCase(mbsPcDataVo.getPcGrade(), "4") || StringUtils.isEmpty(mbsPcDataVo.getPcGrade())) {//公司或职能部门
                                        isNew = true;
                                        SCompany sCompany = null;
                                        List<SCompany> lstSCompany = sCompanyService.getSCompanyByCodeAndRegionalCompanyId(mbsPcDataVo.getPcCode(), null);
                                        if (CollectionUtils.isNotEmpty(lstSCompany)) {
                                            sCompany = lstSCompany.get(0);
                                            isNew = false;
                                        } else {
                                            sCompany = new SCompany();
                                        }
                                        sCompany.setCompanyName(mbsPcDataVo.getPcName());
                                        sCompany.setCompanyCode(mbsPcDataVo.getPcCode());
                                        sCompany.setRegionalCompanyId(sRegionalCompany.getId());
                                        if (isNew) {
                                            sCompany.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
                                            sCompany.setId(IdGenUtils.uuid());
                                            sCompanyService.insert(sCompany);
                                        } else {
                                            sCompany.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, false);
                                            sCompanyService.updateById(sCompany);
                                        }
                                        mapCompany.put(mbsPcDataVo.getPcCode(), sCompany);
                                    }
                                }
                            }

                            LicenseUtil.INSTANCE.validate();
                            //
                            ////保存项目
                            if (CollectionUtils.isNotEmpty(mbsPcTagDataVo.getChildList())) {
                                for (MbsPcDataVo item : mbsPcTagDataVo.getChildList()) {
                                    if (StringUtils.equalsIgnoreCase(item.getPcGrade(), "1")) {
                                        isNew = true;
                                        SProject sProject = null;
                                        String regionalCompanyId = "";
                                        String companyId = "";
                                        SCompany sCompany = mapCompany.get(item.getPcFather());
                                        if (sCompany != null) {
                                            regionalCompanyId = sCompany.getRegionalCompanyId();
                                            companyId = sCompany.getId();
                                        }
                                        ///
                                        List<SProject> lstSProject = sProjectService.getSProjectByCodeAndRegionalCompanyId(item.getPcCode(), null, null);
                                        if (CollectionUtils.isNotEmpty(lstSProject)) {
                                            sProject = lstSProject.get(0);
                                            isNew = false;
                                        } else {
                                            sProject = new SProject();
                                        }
                                        sProject.setRegionalCompanyId(regionalCompanyId);
                                        sProject.setCompanyId(companyId);
                                        sProject.setProjectName(item.getPcName());
                                        sProject.setProjectCode(item.getPcCode());
                                        if (isNew) {
                                            sProject.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
                                            sProject.setId(IdGenUtils.uuid());
                                            sProjectService.insert(sProject);
                                        } else {
                                            sProject.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, false);
                                            sProjectService.updateById(sProject);
                                        }
                                    }
                                }
                            }
                        }
                    }


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /***
     * 从mbs同步供应商内部业绩数据
     */
    @Override
    public void synSupplierInternalPerformance() {
        try {
            Gson gson = new Gson();
            LicenseUtil.INSTANCE.validate();
            SysDict sysDict = sysDictService.getSysDictByValueAndType(CommonConstants.SYS_DICT_VALUE_MBS_SUPPLIER_INTERNAL_PERFORMANCE, CommonConstants.SYS_DICT_TYPE_MBS_SYNS);
            if (sysDict != null) {
                String startTime = sysDict.getDictLabel();
                if(StringUtils.isNotEmpty(startTime)){
                    String returnJson = mbsDataAuthClient.getCtrContentByTime(startTime);
                    if(StringUtils.isNotEmpty(returnJson)){
                        RestReturnResult<List<MbsSupplierInternalPerformance>> result = gson.fromJson(returnJson, new TypeToken<RestReturnResult<List<MbsSupplierInternalPerformance>>>(){}.getType());
                        if(result!=null){
                            if(CollectionUtils.isNotEmpty(result.getData())){
                                for (MbsSupplierInternalPerformance item : result.getData()){
                                    boolean isNew = true;
                                    SSuppliersLastThreeAchieve sSuppliersLastThreeAchieve = new SSuppliersLastThreeAchieve();
                                    ///
                                    EntityWrapper wrapper = new EntityWrapper<>();
                                    SSuppliersLastThreeAchieve selectSSuppliersLastThreeAchieve = new SSuppliersLastThreeAchieve();
                                    selectSSuppliersLastThreeAchieve.setContactCode(item.getCC_Code());
                                    selectSSuppliersLastThreeAchieve.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
                                    wrapper.setEntity(selectSSuppliersLastThreeAchieve);
                                    List<SSuppliersLastThreeAchieve> sSuppliersLastThreeAchievelsMajor = sSuppliersLastThreeAchieveService.selectList(wrapper);
                                    if (CollectionUtils.isNotEmpty(sSuppliersLastThreeAchievelsMajor)) {
                                        sSuppliersLastThreeAchieve = sSuppliersLastThreeAchievelsMajor.get(0);
                                        sSuppliersLastThreeAchieve.setUpdateDate(DateUtils.parseDate(item.getCC_CreateDate()));
                                        isNew = false;
                                    }else{
                                        isNew = true;
                                        sSuppliersLastThreeAchieve.setBaseFeilds(null,null,CommonConstants.NO_INTEGER,true);
                                        sSuppliersLastThreeAchieve.setCreateDate(DateUtils.parseDate(item.getCC_CreateDate()));
                                    }

                                    sSuppliersLastThreeAchieve.setSuppliersId(item.getCS_SpId()+"");
                                    sSuppliersLastThreeAchieve.setCooperativeUnitName(item.getCC_ComName());
                                    sSuppliersLastThreeAchieve.setContactTypeCode(item.getCC_TypeCode());
                                    sSuppliersLastThreeAchieve.setContactTypeName(item.getCC_Type());
                                    sSuppliersLastThreeAchieve.setContactCode(item.getCC_Code());
                                    sSuppliersLastThreeAchieve.setContactName(item.getCC_Name());
                                    sSuppliersLastThreeAchieve.setSignTime(DateUtils.parseDate(item.getCC_SignDate()));
                                    sSuppliersLastThreeAchieve.setCooperativeStartTime(DateUtils.parseDate(item.getCC_StartDate()));
                                    sSuppliersLastThreeAchieve.setCooperativeEndTime(DateUtils.parseDate(item.getCC_FinishDate()));
                                    if(StringUtils.isNotEmpty(item.getCC_Settled())){
                                        SysDict contactStatusSynDict = sysDictService.getSysDictByValueAndType(item.getCC_Settled(), CommonConstants.SYS_DICT_TYPE_CONTACT_STATUS_MBS_MAPPING);
                                        if(contactStatusSynDict!=null){
                                            sSuppliersLastThreeAchieve.setContactStatus(NumberUtils.toInteger(contactStatusSynDict.getDictLabel()));
                                        }
                                    }
                                    sSuppliersLastThreeAchieve.setSignContactPrice(item.getCC_SignValue());
                                    sSuppliersLastThreeAchieve.setActualContactPrice(item.getCC_CtrValue());
                                    sSuppliersLastThreeAchieve.setSourceType(1);//来源（0：外部，1：内部）

                                    sSuppliersLastThreeAchieve.setCooperativeProjectCode(item.getCC_PjCode());
                                    sSuppliersLastThreeAchieve.setCooperativeProjectName(item.getCC_PjName());
                                    if(StringUtils.isNotEmpty(item.getCC_PjCode())) {
                                        List<SProject> lstSProject = sProjectService.getSProjectByCodeAndRegionalCompanyId(item.getCC_PjCode(), null,null);
                                        if(CollectionUtils.isNotEmpty(lstSProject)){
                                            sSuppliersLastThreeAchieve.setCooperativeProjectId(lstSProject.get(0).getId());
                                            sSuppliersLastThreeAchieve.setRegionalCompanyId(lstSProject.get(0).getRegionalCompanyId());
                                            sSuppliersLastThreeAchieve.setCompanyId(lstSProject.get(0).getCompanyId());
                                        }
                                    }

                                    if(isNew){
                                        sSuppliersLastThreeAchieveService.insert(sSuppliersLastThreeAchieve);
                                    }else{
                                        sSuppliersLastThreeAchieveService.updateById(sSuppliersLastThreeAchieve);
                                    }
                                }
                            }

                            LicenseUtil.INSTANCE.validate();
                            //更新最后同步时间
                            SysDict updateSysDict = new SysDict();
                            updateSysDict.setId(sysDict.getId());
                            updateSysDict.setDictLabel(DateUtils.getDate());
                            updateSysDict.setUpdateDate(DateUtils.getNow());
                            sysDictService.updateById(updateSysDict);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /***
     * 从mbs同步战略协议数据
     */
    public void synStrategicProtocols(){
        try {
            Gson gson = new Gson();
            SysDict sysDict = sysDictService.getSysDictByValueAndType(CommonConstants.SYS_DICT_VALUE_MBS_STRATEGIC_PROTOCOL, CommonConstants.SYS_DICT_TYPE_MBS_SYNS);
            if (sysDict != null) {
                String startTime = sysDict.getDictLabel();
                LicenseUtil.INSTANCE.validate();
                if(StringUtils.isNotEmpty(startTime)){
                    String returnJson = mbsDataAuthClient.strategicAgreement(startTime,DateUtils.getDate());
                    if(StringUtils.isNotEmpty(returnJson)){
                        RestReturnResult<List<MbsStrategicProtocols>> result = gson.fromJson(returnJson, new TypeToken<RestReturnResult<List<MbsStrategicProtocols>>>(){}.getType());
                        if(result!=null){
                            if(CollectionUtils.isNotEmpty(result.getData())) {
                                for (MbsStrategicProtocols item : result.getData()) {
                                    WStrategicProtocol wStrategicProtocol = new WStrategicProtocol();
                                    ////
                                    boolean isNew = false;
                                    Map<String,Object> mapParams = new HashMap<String,Object>();
                                    mapParams.put("strategicProtocolSynId",item.getCC_Id());
                                    List<ExtWStrategicProtocol> lstExtWStrategicProtocol = wStrategicProtocolService.findWStrategicProtocolByStrategicProtocolSynId(mapParams);
                                    if(CollectionUtils.isNotEmpty(lstExtWStrategicProtocol)){
                                        ExtWStrategicProtocol extWStrategicProtocol = lstExtWStrategicProtocol.get(0);
                                        wStrategicProtocol.setId(extWStrategicProtocol.getId());
                                        isNew = false;
                                    }else{
                                        wStrategicProtocol.setStrategicStatus(CommonConstants.YES_INTEGER);
                                        wStrategicProtocol.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
                                        isNew = true;
                                    }
                                    wStrategicProtocol.setStrategicName(item.getCC_Name());
                                    wStrategicProtocol.setStrategicProtocolSynId(item.getCC_Id());
                                    wStrategicProtocol.setStrategicCategoryName(item.getSC_TypeName());
                                    wStrategicProtocol.setProtocolStartTime(DateUtils.parseDate(item.getSS_StartDate()));
                                    wStrategicProtocol.setProtocolEndTime(DateUtils.parseDate(item.getSS_EndDate()));
                                    wStrategicProtocol.setContactName(item.getSP_Name());
                                    wStrategicProtocol.setContactInfo(item.getSP_Cell());
                                    wStrategicProtocol.setStrategicProtocolUrl(item.getCC_Url());
                                    wStrategicProtocol.setSupplierName(item.getSC_Name());
                                    if(StringUtils.isNotEmpty(item.getSC_Id()) || StringUtils.isNotEmpty(item.getSC_Code())){
                                        Map<String, Object> mapParam = new HashMap<String, Object>();
                                        mapParam.put("id",item.getSC_Id());
                                        mapParam.put("companyCode",item.getSC_Code());
                                        List<ExtSSuppliers> lstExtSSuppliers = sSuppliersService.getSuppliersByIdOrCode(mapParam);
                                        if(CollectionUtils.isNotEmpty(lstExtSSuppliers)){
                                            wStrategicProtocol.setSupplierId(lstExtSSuppliers.get(0).getId());
                                        }
                                    }
                                    if(StringUtils.isEmpty(wStrategicProtocol.getSupplierId())){
                                        wStrategicProtocol.setSupplierId(item.getSC_Id());
                                    }

                                    if(isNew){
                                        wStrategicProtocolService.insert(wStrategicProtocol);
                                    }else{
                                        wStrategicProtocolService.updateById(wStrategicProtocol);
                                    }

                                }
                            }

                            LicenseUtil.INSTANCE.validate();
                            //更新最后同步时间
                            SysDict updateSysDict = new SysDict();
                            updateSysDict.setId(sysDict.getId());
                            updateSysDict.setDictLabel(DateUtils.getDate());
                            updateSysDict.setUpdateDate(DateUtils.getNow());
                            sysDictService.updateById(updateSysDict);
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
